<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: `${editing ? '修改' : '新增'}渠道活码`,
			size: '820px'
		}"
		show-confirm
		confirm-text="提交"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="saving">
			<el-form-item label="基础设置">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="所属事业部" prop="biz_id">
								<cl-select
									v-model="form.biz_id"
									style="width:100%;"
									placeholder="请选择事业部"
									filterable
									:disabled="editing"
									@change="changeBiz"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="品牌" prop="bra_id">
								<cl-select
									v-model="form.bra_id"
									placeholder="请选择品牌"
									filterable
									style="width: 100%"
									@change="changeBra"
								>
									<el-option
										v-for="item in brandList"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-form-item label="活码名称" prop="name">
						<el-input
							v-model.trim="form.name"
							placeholder="请输入活码名称"
							maxlength="30"
							show-word-limit
							:disabled="editing"
						/>
					</el-form-item>
					<el-form-item label="自动添加好友" prop="skip_verify" style="margin-bottom:0">
						<el-switch
							:active-value="1"
							:inactive-value="0"
							v-model="form.skip_verify"
						/>
						<span class="tips">
							{{
								form.skip_verify
									? "（开启时，客户扫码添加成员自动成员好友，无需确认）"
									: "（关闭时，客户扫码添加成员需成员确认）"
							}}
						</span>
					</el-form-item>
				</el-card>
			</el-form-item>

			<el-form-item label="引流成员设置">
				<el-card shadow="never">
					<el-form-item label="活码类型" prop="code_type">
						<el-radio-group
							v-model="form.code_type"
							:disabled="editing"
							@change="changeCodeType"
						>
							<el-radio :label="1">单人</el-radio>
							<el-radio :label="2">多人</el-radio>
						</el-radio-group>
						<div class="tips">
							{{
								form.code_type == 1
									? "（当客户通过活码扫码添加好友时，所加为好友的成员为设置的成员,创建成功后不可修改）"
									: "（当客户通过活码扫码添加好友时，所加为好友的成员为将从设置的成员中随机分配,创建成功后不可修改）"
							}}
						</div>
					</el-form-item>
					<el-form-item
						label="企业成员"
						:key="form.code_type == 1"
						:prop="form.code_type == 1 ? 'user_id' : 'user_ids'"
						:rules="rules.user_ids"
					>
						<cl-select
							v-if="form.code_type == 1"
							v-model="form.user_id"
							style="width:100%"
							filterable
							@change="setStaff"
						>
							<el-option
								v-for="item in staffList"
								:key="item.user_id"
								:label="item.user_name"
								:value="item.user_id"
							/>
						</cl-select>
						<cl-select
							v-else
							v-model="form.user_ids"
							style="width:100%"
							multiple
							filterable
							@change="setStaff"
						>
							<el-option
								v-for="item in staffList"
								:key="item.user_id"
								:label="item.user_name"
								:value="item.user_id"
							/>
						</cl-select>
					</el-form-item>
					<el-form-item label="员工添加上限" prop="is_add_limit">
						<el-switch
							@change="changeAddswitch"
							v-model="form.is_add_limit"
							:active-value="1"
							:inactive-value="0"
						/>
						<span class="tips">
							（因受官方限制，无法对动态部门的员工设置添加好友上限，只可针对指定活码成员进行设置）
						</span>
					</el-form-item>
					<el-collapse-transition>
						<div v-if="form.user_list.length && form.is_add_limit == 1">
							<zm-table v-bind="table" :data="form.user_list">
								<template #column-limit="{scope:{row,$index}}">
									<el-form-item
										:prop="`user_list.${$index}.limit`"
										:show-message="false"
										status-icon
										:rules="rules.user_limit"
										style="margin-bottom:0"
									>
										<el-input
											v-model.number="row.limit"
											oninput="value=value.replace(/[^\d]/g,'')"
											placeholder="请输入员工上限"
										/>
									</el-form-item>
								</template>
							</zm-table>
							<el-form-item label="备用员工" prop="spare_staff_id" class="mt-1">
								<cl-select
									v-model="form.spare_staff_id"
									style="width: 100%"
									placeholder="请选择备用员工"
									filterable
								>
									<el-option
										v-for="item in staffList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</el-form-item>
						</div>
					</el-collapse-transition>
				</el-card>
			</el-form-item>
			<el-form-item label="欢迎语设置">
				<el-card shadow="never" class="welcome-conf">
					<el-row type="flex">
						<phone>
							<div class="message" v-show="!!form.welcome_data">
								<cl-avatar size="medium" :src="require('@/assets/img/men.png')" />
								<div class="input-value" v-html="form.welcome_data" />
							</div>
						</phone>
						<cl-flex1 class="ml-2" style="overflow: hidden;">
							<div class="operate">
								<div
									contenteditable="true"
									id="textarea"
									class="custom-textarea"
									ref="custom-textarea"
									@input="changeWelcome"
								/>
								<span>{{ textLength }}/1000</span>
								<div class="btns">
									<span>点击插入：</span>
									<el-button class="btn-orange" @click="handleAddBtn">
										客户名称
									</el-button>
								</div>
							</div>
						</cl-flex1>
					</el-row>
				</el-card>
			</el-form-item>
		</el-form>
	</cl-drawer>
</template>
<script>
import Phone from "./phone";
export default {
	components: {
		Phone
	},
	data() {
		return {
			saving: false,
			editing: false,
			form: {
				id: undefined,
				biz_id: "",
				bra_id: "",
				name: "",
				skip_verify: 1,
				code_type: 1,
				user_id: "",
				user_ids: [],
				is_add_limit: 0,
				user_list: [],
				spare_staff_id: "",
				welcome_data: ""
			},
			rules: {
				biz_id: [{ required: true, message: "请选择事业部" }],
				bra_id: [{ required: true, message: "请选择品牌" }],
				name: [{ required: true, message: "请输入活码名称" }],
				user_ids: [{ required: true, message: "请选择企业成员" }],
				user_limit: [
					{ required: true, type: "number", message: "请输入员工上限" },
					{ type: "number", min: 1, max: 500, message: "员工上限数量必须1-500之间" }
				],
				spare_staff_id: [{ required: true, message: "请选择备用员工" }]
			},
			// 品牌列表
			brandList: [],
			staffList: [],
			table: {
				"context-menu": [],
				autoHeight: false,
				columns: [
					{ type: "index", label: "#", align: "center", width: 50 },
					{ label: "员工名称", prop: "user_name", minWidth: 150 },
					{ label: "上限", prop: "limit", minWidth: 150 }
				]
			},
			cusTemp: `<span contenteditable="false" class="custom-span">客户名称</span>`,
			textLength: 0
		};
	},

	created() {
		this.form.biz_id = this.getCurrBiz();
	},
	methods: {
		open(editing = false, data = {}) {
			this.editing = editing;
			this.$refs.drawer.create(async () => {
				this.reset();
				if (editing) {
					Object.keys(this.form).forEach(k => {
						data[k] != undefined && (this.form[k] = data[k]);
					});
				}
				if (data.code_type == 1) {
					this.form.user_id = data.wxk_staff_id;
				} else {
					this.form.user_ids = data.wxk_staff_id
						?.split?.(",")
						.filter(Boolean)
						.map(Number);
				}
				this.form.welcome_data = (data.welcome_data ?? "")
					.split("{name}")
					.join(this.cusTemp + " ");
				await Promise.all([this.getBrand(), this.getStaff()]);
			});
		},
		//切换事业部
		changeBiz() {
			this.form.bra_id = "";
			this.getBrand();
			this.getStaff();
		},
		changeBra() {
			this.setStaff();
			this.getStaff();
		},
		// 品牌
		async getBrand() {
			this.brandList = await this.$store.dispatch("common/getBizBrands", {
				biz_id: this.form.biz_id,
				needAll: false
			});
		},
		// 获取员工
		async getStaff() {
			const { biz_id, bra_id } = this.form;
			if (!bra_id) {
				this.staffList = [];
				return;
			}
			let list = (await this.$service.workwechat.userList({ biz_id, bra_id })) || [];
			this.staffList = list.map(v => ({ user_id: v.user_id, user_name: v.name }));
		},
		changeCodeType() {
			this.form.is_add_limit = 0;
			this.form.user_id = "";
			this.form.user_ids = [];
			this.form.user_list = [];
		},
		// 添加员工
		setStaff() {
			const { code_type, user_id, user_ids } = this.form;
			if (code_type == 1 && user_id) {
				let staff = this.staffList.find(item => item.user_id == user_id) || { user_id: 0 };
				this.form.user_list = [{ ...staff, limit: 100 }];
				return;
			}
			let staffs = this.staffList.filter(item => user_ids.includes(item.user_id));
			this.form.user_list = staffs.map(v => ({ ...v, limit: 100 }));
		},
		// 员工添加上限
		changeAddswitch() {
			const { user_list } = this.form;
			if (!user_list.length) {
				this.$message.closeAll();
				this.$message.warning("请先选择成员");
				this.form.is_add_limit = 0;
				return;
			}
			this.setStaff();
		},
		//点击插入
		handleAddBtn() {
			let oDiv = this.$refs["custom-textarea"];
			oDiv.focus();
			if (1000 - this.textLength >= 4) {
				this.pasteHtmlAtCaret(this.cusTemp + " ");
				this.form.welcome_data = oDiv.innerHTML;
				this.textLength = oDiv.textContent.length;
			}
		},
		// 插入客户名称
		pasteHtmlAtCaret(html) {
			if (window.getSelection) {
				let sel = window.getSelection();
				if (sel.getRangeAt && sel.rangeCount) {
					let range = sel.getRangeAt(0);
					range.deleteContents();
					let el = document.createElement("div");
					el.innerHTML = html;
					let frag = document.createDocumentFragment(),
						node,
						lastNode;
					while ((node = el.firstChild)) {
						lastNode = frag.appendChild(node);
					}
					range.insertNode(frag);
					if (lastNode) {
						range = range.cloneRange();
						range.setStartAfter(lastNode);
						range.collapse(true);
						sel.removeAllRanges();
						sel.addRange(range);
					}
				}
			} else if (document.selection && document.selection.type != "Control") {
				// IE < 9
				document.selection.createRange().pasteHTML(html);
			}
		},
		// 监听输入框变化
		changeWelcome(e) {
			let oDiv = this.$refs["custom-textarea"];
			this.form.welcome_data = oDiv.innerHTML;
			this.textLength = oDiv.textContent.length;
			if (this.textLength >= 1000) {
				this.textLength = 1000;
				this.form.welcome_data = oDiv.textContent.slice(0, this.textLength + 1);
				oDiv.innerHTML = this.form.welcome_data;
			}
		},
		close() {
			this.$refs.drawer.close();
		},
		reset() {
			this.saving = false;
			this.form.biz_id = this.getCurrBiz();
			this.form.user_id = "";
			this.form.user_ids = [];
			this.form.welcome_data = "";
			this.textLength = 0;
			this.$refs.form.resetFields();
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;
				this.saving = true;
				let { welcome_data, user_list, user_id, user_ids, ...args } = this.form;
				let form = {
					...args,
					config_id: args.id,
					wxk_staff_id: args.code_type == 1 ? user_id : user_ids.join(),
					remark: welcome_data
						.split(this.cusTemp)
						.join("{name}")
						.split("<div>")
						.join("<br>")
						.split("</div>")
						.join("")
						.split("<p>")
						.join("<br>")
						.split("</p>")
						.join("")
				};
				await this.$service.workwechat[this.editing ? "updateContactWay" : "addContactWay"](
					form
				).done(() => {
					this.saving = false;
				});
				this.$message.success(`${this.editing ? "修改" : "新增"}配置成功`);
				this.$emit("confirm", !this.editing);
				this.reset();
				this.close();
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.tips {
	color: #909399;
	font-size: 12px;
	line-height: 1.5;
}
.welcome-conf {
	.message {
		display: flex;
		padding: 10px;
		.input-value {
			flex: 1;
			padding: 6px 8px;
			min-height: 40px;
			line-height: 1.5;
			font-size: 14px;
			color: #333;
			background-color: #fff;
			margin-left: 10px;
			box-shadow: 0px 0px 12px 0px rgba(47, 75, 168, 0.06);
			border-radius: 4px 12px 12px 12px;
			overflow-x: hidden;
			overflow-y: auto;
			word-wrap: break-word;
		}
	}
	.operate {
		position: relative;
		background: #fff;
		border-radius: 8px;
		border: 1px solid #b9c5e9;
		padding: 10px;
		color: #333;
		font-size: 14px;
		box-sizing: border-box;

		> span {
			position: absolute;
			top: 220px;
			right: 20px;
			font-size: 12px;
			color: #999;
		}

		.btns {
			margin: 10px 0 0;
			user-select: none;
			.btn-orange {
				font-weight: bold;
				color: #fea96c;
				border-radius: 4px;
				background: #fff7e6;
				border: 1px solid #f5daa3;
			}
		}

		.custom-textarea {
			user-select: text;
			font-size: 14px;
			color: #333;
			height: 240px;
			padding: 10px 10px 20px;
			background: #ffffff;
			border-radius: 4px;
			border: 1px solid #b9c5e9;
			outline: none;
			overflow-x: hidden;
			overflow-y: auto;
			word-wrap: break-word;
			user-select: none;
			box-sizing: border-box;
			caret-color: $primary;
			&::-webkit-scrollbar {
				width: 5px;
				height: 5px;
			}
		}
	}
	::v-deep .custom-span {
		display: inline-block;
		font-weight: bold;
		color: #fea96c;
		border-radius: 5px;
		background: #fff7e6;
		border: 1px solid #f5daa3;
		padding: 0 5px;
		height: 30px;
		line-height: 30px;
		margin: 3px 0;
		text-align: center;
		box-sizing: border-box;
	}
}
</style>
